package de.herberlin.webapp.text;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import de.herberlin.webapp.core.Functions;

/**
 * PageFilter.java
 *
 * Created on 14. Oktober 2007, 21:48
 *
 * @author herberlin
 */
public class PageFilter implements Filter{

   
    @SuppressWarnings("unused")
	private FilterConfig filterConfig=null;
    
    private Log logger=LogFactory.getLog(getClass());
    
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig=filterConfig;
        logger.debug("FilterConfig="+filterConfig);
    }
    
    
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
            FilterChain filterChain) throws IOException, ServletException {
        
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        
        Page page=Functions.getPage(request);
        logger.debug("Page="+page);

        if (page==null) {
            request.getRequestDispatcher("/404.jsp").include(request,servletResponse);
        } else {
            request.setAttribute("content",page);
            logger.debug("Text="+page.getText());
            request.setAttribute("pageId", page.getId());
            request.getRequestDispatcher(getTemplate(page)).include(request,servletResponse);
        }
        
        // filterChain.doFilter(request, servletResponse);

    }
    
    
    private String getTemplate(Page page) {
        String tp=page.getTemplate();
        if (tp==null) {
            tp="standard";
        }
        return "/WEB-INF/includes/"+tp+".jsp";
    }
    
     
    public void destroy() {
    }

    
}
